﻿using System;
using System.Collections.Generic;
using System.Text;
using Memcached.ClientLibrary;
using System.Data;
using System.Collections;

namespace Core.Memceched
{
    public class Cache_Info
    {
        private readonly static string CacheKey = "Info_key";

        private static bool IsCache(MemcachedClient pMC, string pKey)
        {
            if (pMC.KeyExists(pKey))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private static bool StoreCache(string pKey, object pObject)
        {
            MemcachedClient mc = new MemcachedClient();
            mc.EnableCompression = true;
            bool _result = false;
            if (IsCache(mc, pKey))
            {
                if (mc.Get(pKey) == null)
                {
                    mc.Set(pKey, pObject);//缓存存在，强行覆盖
                }
                else
                {
                    mc.Replace(pKey, pObject);//缓存存在，强行覆盖
                }
                _result = true;
            }
            else
            {
                mc.Add(pKey, pObject);//第一次加载缓存
                _result = true;
            }
            return _result;
        }

        public static bool RemoveCache(string pKey)
        {
            MemcachedClient mc = new MemcachedClient();
            mc.EnableCompression = true;
            return mc.Delete(pKey);
        }

        public static Hashtable GetInfo()
        {
            MemcachedClient mc = new MemcachedClient();
            mc.EnableCompression = true;
            if (mc.Get(CacheKey) != null)
            {
                return mc.Get(CacheKey) as Hashtable;
            }
            else
            {
                List<string> ht = new List<string>();
                ht.Add("11111");
                ht.Add("22222");
                ht.Add("33333");
                if (StoreCache(CacheKey, ht))
                {
                    return mc.Get(CacheKey) as Hashtable;
                }
                else
                {
                    return null;
                }
            }
        }
    }
}
